package com.leadbank.example.controller;

import com.leadbank.example.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created by hp on 2019/4/24.
 */
@RequestMapping("/movies")
@RestController
public class MovieController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;// Eureka客户端，可以获取到服务实例信息

    @GetMapping("/users/{id}")
    public User findByid(@PathVariable Long id) {
        // 这里用到了RestTemplate的占位符能力
        //User user = restTemplate.getForObject("http://localhost:8001/users/{id}",User.class,id);
        // 根据服务名称，获取服务实例
        List<ServiceInstance> instances = discoveryClient.getInstances("microservice-simple-provider-user");
        // 因为只有一个UserService,因此我们直接get(0)获取
        ServiceInstance instance = instances.get(0);
        // 获取ip和端口信息
        String baseUrl = "http://"+instance.getHost()+":"+instance.getPort()+"/users/" + id;

        User user = restTemplate.getForObject(baseUrl, User.class);

        // ...电影微服务的业务...
        return user;
    }
}
